package com.cms.edm.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cms.edm.dao.TeacherDao;
import com.cms.edm.entity.TeacherEntity;
import com.cms.edm.entity.vo.CourseListVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cms.common.utils.PageUtils;
import com.cms.common.utils.Query;

import com.cms.edm.dao.CourseDao;
import com.cms.edm.entity.CourseEntity;
import com.cms.edm.service.CourseService;

import javax.annotation.Resource;


@Service("courseService")
public class CourseServiceImpl extends ServiceImpl<CourseDao, CourseEntity> implements CourseService {

    @Resource
    private TeacherDao teacherDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String) params.get("key");
        QueryWrapper<CourseEntity> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            wrapper.like("name", key).or().eq("id", key);
        }

        IPage<CourseEntity> page = this.page(
                new Query<CourseEntity>().getPage(params),
                wrapper
        );

        List<CourseEntity> records = page.getRecords();
        List<CourseListVo> result = new ArrayList<>();
        for (CourseEntity record : records) {
            TeacherEntity teacherEntity = teacherDao.selectById(record.getTeacherId());
            CourseListVo courseListVo = new CourseListVo();
            BeanUtils.copyProperties(record, courseListVo);
            courseListVo.setTeacherName(teacherEntity.getName());
            result.add(courseListVo);
        }

        IPage<CourseListVo> resultPage =  new Page<>();
        resultPage.setRecords(result);
        resultPage.setCurrent(page.getCurrent());
        resultPage.setPages(page.getPages());
        resultPage.setSize(page.getSize());
        resultPage.setTotal(page.getTotal());

        return new PageUtils(resultPage);
    }

    @Override
    public List<TeacherEntity> selectTeacher(String courseName) {
        QueryWrapper<TeacherEntity> wrapper = new QueryWrapper<>();
        wrapper.like("main", courseName).or().like("minor", courseName);
        return teacherDao.selectList(wrapper);
    }

}